<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <!-- <el-form-item label="用户id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
       <el-form-item label="优惠券模板" prop="couponTempId">
        <el-select
                    v-model="queryParams.couponTempId"
                    clearable
                    @keyup.enter.native="handleQuery"
                    placeholder="请选择优惠券模板" 
                  >
                    <el-option
                      v-for="dict in usercouponListSelect"
                      :key="dict.id"
                      :label="dict.name"
                      :value="dict.id"
                    />
                  </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
                    v-model="queryParams.status"
                    clearable
                    placeholder="请选择状态" 
                  >
                    <el-option
                      v-for="dict in dict.type.coupon_temp_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
      </el-form-item>
      <!-- <el-form-item label="满减金额" prop="fullAmount">
        <el-input
          v-model="queryParams.fullAmount"
          placeholder="请输入满减金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="生效时间" prop="effectiveStartTime">
        <el-date-picker clearable
          v-model="queryParams.effectiveStartTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择生效时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="失效时间" prop="effectiveEndTime">
        <el-date-picker clearable
          v-model="queryParams.effectiveEndTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择失效时间">
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="使用时间" prop="useTime">
        <el-date-picker clearable
          v-model="queryParams.useTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择使用时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['usercoupon:usercoupon:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['usercoupon:usercoupon:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['usercoupon:usercoupon:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['usercoupon:usercoupon:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="usercouponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="ID" align="center" prop="id" /> -->
      <el-table-column label="用户" align="center" prop="userName" />
      <el-table-column label="优惠券模板" align="center" prop="couponTempName" />
      <el-table-column label="优惠类型" align="center" prop="couponType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.coupon_type" :value="scope.row.couponType"/>
        </template>
      </el-table-column>
      <el-table-column label="优惠金额" align="center" prop="couponAmount" >
        <template slot-scope="scope">
          <span>{{scope.row.couponAmount?scope.row.couponAmount/100:''}}</span>
        </template>
      </el-table-column>
      <el-table-column label="满减金额" align="center" prop="fullAmount" />
      <el-table-column label="使用时间" align="center" prop="useTime" width="180">
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.coupon_temp_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="使用时间" align="center" prop="useTime" width="180">
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCancel(scope.row)"
            v-hasPermi="['usercoupon:usercoupon:edit']"
          >作废</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['usercoupon:usercoupon:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body :close-on-click-modal="dialogIsCloseOnModal" :close-on-press-escape="dialogIsCloseOnModal">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
        <el-col :span="24">
            <el-col :span="11">
              <el-form-item label="优惠券模板" prop="couponTempId">
                <el-select
                    v-model="form.couponTempId"
                    clearable
                    @change='changeScenicSelect'
                    placeholder="请输入优惠券模板" 
                  >
                    <el-option
                      v-for="dict in usercouponListSelect"
                      :key="dict.id"
                      :label="dict.name"
                      :value="dict.id"
                    />
                  </el-select>
                </el-form-item>
            </el-col>
        </el-col>
        <!-- 选择优惠券后展示详细信息 -->
          <el-col :span="24" v-if='form.couponTempId'>
            <el-col :span="11">
            <el-form-item label="优惠金额" prop="couponAmout">
              <el-input-number v-model="usercouponSelected.couponAmout/100" placeholder="请输入优惠金额" :min="0" disabled controls-position="right"/>
            </el-form-item>
            </el-col>
            <el-col :span="12">
            <el-form-item label="发放数量" prop="quantity">
              <el-input-number v-model="usercouponSelected.quantity" placeholder="请输入发放数量" :min="0" disabled controls-position="right"/>
            </el-form-item>
             </el-col>
            <el-col :span="11">
              <el-form-item label="生效时间" prop="effectiveStartTime" >
                <el-date-picker clearable disabled
                  v-model="usercouponSelected.effectiveStartTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择生效时间"
                  default-time="08:30:00">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="失效时间" prop="effectiveEndTime" >
                <el-date-picker clearable disabled
                  v-model="usercouponSelected.effectiveEndTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择失效时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <!-- <el-form-item label="使用时间" prop="useTime">
              <el-date-picker clearable
                v-model="form.useTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择使用时间">
              </el-date-picker>
            </el-form-item> -->
          </el-col>
        </el-row>
        <el-form-item label="选择类型" prop="type">
          <el-radio-group v-model="form.type" @input='clearRulesTip'>
            <el-radio :label="0">单个</el-radio>
            <el-radio :label="1">批量</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-col :span="24">
          <el-col :span="11">
          <el-form-item label="手机号" :prop="form.type==0?'mobile':'empty'" v-if='form.type==0'>
            <el-input v-model="form.mobile" placeholder="请输入手机号码" />
          </el-form-item>
          </el-col>
        </el-col>
        <el-form-item label="附件上传" prop="userId" v-if='form.type==1'>
          <el-upload
              ref="upload"
              :limit="1"
              accept=".xlsx, .xls"
              :headers="upload.headers"
              :action="upload.url + '?updateSupport=' + upload.updateSupport+'&couponTempId='+form.couponTempId"
              :disabled="upload.isUploading"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :auto-upload="false"
              drag
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">
                <span>仅允许导入xls、xlsx格式文件。</span>
                <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
              </div>
            </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUsercoupon, getUsercoupon, delUsercoupon, addUsercoupon, updateUsercoupon,getUsercouponSelect,cancelUsercoupon } from "@/api/usercoupon/usercoupon";
import { getToken } from "@/utils/auth";
export default {
  name: "Usercoupon",
  dicts: ['coupon_type','rule_type','coupon_temp_status'],
  data() {
    return {
      // 优惠券模板下拉
      usercouponListSelect:[],
      // 选中的优惠券模板
      usercouponSelected:'',
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/order/usercoupon/importData"
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户优惠券表格数据
      usercouponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        couponTempId: null,
        couponType: null,
        couponAmount: null,
        fullAmount: null,
        effectiveStartTime: null,
        effectiveEndTime: null,
        status: null,
        useTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        couponTempId:[
          {required:true,message:'请选择优惠券模板',trigger:'change'}
        ],
        mobile: [
          { pattern: /^((0\d{2,3}-?\d{7,8})|(1[3456789]\d{9}))$/,message: "请输入正确的联系电话",trigger: "blur"},
          { required: true, message: "请输入手机号", trigger: "blur",}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getUsercouponList()
  },
  methods: {
    // 优惠券模板下拉列表
    getUsercouponList(){
      getUsercouponSelect().then(res=>{
        console.log(res)
        this.usercouponListSelect=res.data
      })
    },
    // 选中优惠券模板
    changeScenicSelect(val){
      this.usercouponListSelect.map(item=>{
        if(item.id==val){
          this.usercouponSelected=item
        }
      })
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('order/usercoupon/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      console.log(response)
      if(response.code==200){
        this.open=false
        this.getList();
      }
    },
    // 提交上传文件
    submitFileForm() {
      console.log('submit')
      this.$refs.upload.submit()
    },
    clearRulesTip(){
      console.log('clearRulesTip')
      this.$refs.form.clearValidate('mobile');
    },
    /** 查询用户优惠券列表 */
    getList() {
      this.loading = true;
      listUsercoupon(this.queryParams).then(response => {
        this.usercouponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        couponTempId: null,
        couponType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDel: null,
        codeNo: null,
        couponAmount: null,
        fullAmount: null,
        effectiveStartTime: null,
        effectiveEndTime: null,
        status: null,
        useTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户优惠券";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUsercoupon(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户优惠券";
      });
    },
    /** 提交按钮 */
    submitForm() {
      
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUsercoupon(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if(this.form.type==1){
              // 批量
              this.submitFileForm()
            }else{
              addUsercoupon(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
            
          }
        }
      });
    },
    // 作废
    handleCancel(row){
      const ids = row.id 
      this.$modal.confirm('是否确认作废用户优惠券编号为"' + ids + '"的数据项？').then(function() {
        return cancelUsercoupon(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("作废成功");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户优惠券编号为"' + ids + '"的数据项？').then(function() {
        return delUsercoupon(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('usercoupon/usercoupon/export', {
        ...this.queryParams
      }, `usercoupon_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
